<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>家庭记账本 - 收支记录</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background-color: #f8f9fa;
            padding: 20px;
        }
        .main-content {
            padding: 20px;
        }
        .transaction-type-income {
            color: #198754;
        }
        .transaction-type-expense {
            color: #dc3545;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-2 sidebar">
                <h3 class="mb-4">家庭记账本</h3>
                <div class="list-group">
                    <a href="profile" class="list-group-item list-group-item-action">个人中心</a>
                    <a href="dashboard" class="list-group-item list-group-item-action">总账单</a>
                    <a href="transactions" class="list-group-item list-group-item-action active">收支记录</a>
                    <c:if test="${user.isAdmin()}">
                        <a href="users" class="list-group-item list-group-item-action">用户管理</a>
                    </c:if>
                    <a href="logout" class="list-group-item list-group-item-action text-danger">退出登录</a>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-10 main-content">
                <!-- 用户信息展示 -->
                <div class="alert alert-info mb-3" style="padding: 8px 16px;">
                    当前账号：<strong>${sessionScope.user.username}</strong>，姓名：<strong>${sessionScope.user.name}</strong>，身份：
                    <strong>
                        <c:choose>
                            <c:when test="${sessionScope.user.role eq 'GOD'}">超级管理员</c:when>
                            <c:when test="${sessionScope.user.role eq 'ADMIN'}">管理员</c:when>
                            <c:otherwise>普通用户</c:otherwise>
                        </c:choose>
                    </strong>
                </div>
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2>收支记录</h2>
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addTransactionModal">
                        <i class="bi bi-plus-lg"></i> 新增记录
                    </button>
                </div>

                <!-- Filter Form -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form action="${pageContext.request.contextPath}/transactions" method="get" class="row g-3">
                            <div class="col-md-2">
                                <label for="userId" class="form-label">用户</label>
                                <select class="form-select" id="userId" name="userId">
                                    <option value="">全部</option>
                                    <c:forEach items="${allUsers}" var="u">
                                        <option value="${u.id}" ${selectedUserId == u.id ? 'selected' : ''}>${u.username}</option>
                                    </c:forEach>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label for="startDate" class="form-label">开始日期</label>
                                <input type="date" class="form-control" id="startDate" name="startDate" 
                                       value="${param.startDate}">
                            </div>
                            <div class="col-md-3">
                                <label for="endDate" class="form-label">结束日期</label>
                                <input type="date" class="form-control" id="endDate" name="endDate" 
                                       value="${param.endDate}">
                            </div>
                            <div class="col-md-2">
                                <label for="type" class="form-label">类型</label>
                                <select class="form-select" id="type" name="type">
                                    <option value="">全部</option>
                                    <option value="INCOME" ${param.type == 'INCOME' ? 'selected' : ''}>收入</option>
                                    <option value="EXPENSE" ${param.type == 'EXPENSE' ? 'selected' : ''}>支出</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label for="categoryId" class="form-label">分类</label>
                                <select class="form-select" id="categoryId" name="categoryId">
                                    <option value="">全部</option>
                                    <c:forEach items="${categories}" var="category">
                                        <option value="${category.id}" ${param.categoryId == category.id ? 'selected' : ''}>
                                            ${category.name}
                                        </option>
                                    </c:forEach>
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">筛选</button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Transactions Table -->
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>日期</th>
                                        <th>类型</th>
                                        <th>分类</th>
                                        <th>用户</th>
                                        <th>金额</th>
                                        <th>描述</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <c:forEach items="${transactions}" var="transaction">
                                        <tr>
                                            <td>${transaction.transactionDateStr}</td>
                                            <td>
                                                <span class="transaction-type-${transaction.type == 'INCOME' ? 'income' : 'expense'}">
                                                    ${transaction.type == 'INCOME' ? '收入' : '支出'}
                                                </span>
                                            </td>
                                            <td>${transaction.categoryName}</td>
                                            <td>${transaction.userName}</td>
                                            <td class="transaction-type-${transaction.type == 'INCOME' ? 'income' : 'expense'}">
                                                ¥<fmt:formatNumber value="${transaction.amount}" pattern="#,##0.00"/>
                                            </td>
                                            <td>${transaction.description}</td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-outline-primary edit-transaction"
                                                        data-id="${transaction.id}"
                                                        data-type="${transaction.type}"
                                                        data-category-id="${transaction.categoryId}"
                                                        data-amount="${transaction.amount}"
                                                        data-description="${transaction.description}"
                                                        data-date="${transaction.transactionDateStr}">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                                <button type="button" class="btn btn-sm btn-outline-danger delete-transaction"
                                                        data-id="${transaction.id}">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    </c:forEach>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Transaction Modal -->
    <div class="modal fade" id="addTransactionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新增记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="addTransactionForm" action="${pageContext.request.contextPath}/transactions/add" method="post">
                        <div class="mb-3">
                            <label for="transactionType" class="form-label">类型</label>
                            <select class="form-select" id="transactionType" name="type" required>
                                <option value="INCOME">收入</option>
                                <option value="EXPENSE">支出</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="transactionCategory" class="form-label">分类</label>
                            <c:out value="${fn:length(categories)}"/>
                            <select class="form-select" id="transactionCategory" name="categoryId" required>
                                <c:forEach items="${categories}" var="category">
                                    <option value="${category.id}" data-type="${category.type}">
                                        ${category.name}
                                    </option>
                                </c:forEach>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="transactionAmount" class="form-label">金额</label>
                            <input type="number" class="form-control" id="transactionAmount" name="amount" 
                                   step="0.01" min="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label for="transactionDate" class="form-label">日期</label>
                            <input type="date" class="form-control" id="transactionDate" name="transactionDate" 
                                   required>
                        </div>
                        <div class="mb-3">
                            <label for="transactionDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="transactionDescription" name="description" 
                                      rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" form="addTransactionForm" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Transaction Modal -->
    <div class="modal fade" id="editTransactionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editTransactionForm" action="${pageContext.request.contextPath}/transactions/edit" method="post">
                        <input type="hidden" id="editTransactionId" name="id">
                        <div class="mb-3">
                            <label for="editTransactionType" class="form-label">类型</label>
                            <select class="form-select" id="editTransactionType" name="type" required>
                                <option value="INCOME">收入</option>
                                <option value="EXPENSE">支出</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editTransactionCategory" class="form-label">分类</label>
                            <select class="form-select" id="editTransactionCategory" name="categoryId" required>
                                <c:forEach items="${categories}" var="category">
                                    <option value="${category.id}" data-type="${category.type}">
                                        ${category.name}
                                    </option>
                                </c:forEach>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="editTransactionAmount" class="form-label">金额</label>
                            <input type="number" class="form-control" id="editTransactionAmount" name="amount" 
                                   step="0.01" min="0.01" required>
                        </div>
                        <div class="mb-3">
                            <label for="editTransactionDate" class="form-label">日期</label>
                            <input type="date" class="form-control" id="editTransactionDate" name="transactionDate" 
                                   required>
                        </div>
                        <div class="mb-3">
                            <label for="editTransactionDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="editTransactionDescription" name="description" 
                                      rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" form="editTransactionForm" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Transaction Modal -->
    <div class="modal fade" id="deleteTransactionModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除这条记录吗？此操作不可恢复。</p>
                    <form id="deleteTransactionForm" action="${pageContext.request.contextPath}/transactions/delete" method="post">
                        <input type="hidden" id="deleteTransactionId" name="id">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" form="deleteTransactionForm" class="btn btn-danger">删除</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Set default date to today
        document.getElementById('transactionDate').valueAsDate = new Date();

        // 分类过滤（只保留这一套）
        function filterCategories(type) {
            const options = document.querySelectorAll('#transactionCategory option');
            options.forEach(option => {
                if (!option.value) return; // 跳过空选项
                const categoryType = option.dataset.type;
                option.style.display = (categoryType === type) ? '' : 'none';
            });
            // 自动选中第一个可见项
            const firstVisible = Array.from(options).find(opt => opt.style.display !== 'none' && opt.value);
            if (firstVisible) {
                document.getElementById('transactionCategory').value = firstVisible.value;
            } else {
                document.getElementById('transactionCategory').value = '';
            }
        }
        document.getElementById('transactionType').addEventListener('change', function() {
            filterCategories(this.value);
        });
        document.addEventListener('DOMContentLoaded', function() {
            filterCategories(document.getElementById('transactionType').value);
        });
        // 其他弹窗和表格相关 JS 保持不变
        // Edit transaction modal
        document.querySelectorAll('.edit-transaction').forEach(button => {
            button.addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('editTransactionModal'));
                const data = this.dataset;
                document.getElementById('editTransactionId').value = data.id;
                document.getElementById('editTransactionType').value = data.type;
                document.getElementById('editTransactionCategory').value = data.categoryId;
                document.getElementById('editTransactionAmount').value = data.amount;
                document.getElementById('editTransactionDate').value = data.date;
                document.getElementById('editTransactionDescription').value = data.description;
                filterCategories(data.type);
                modal.show();
            });
        });
        // Delete transaction modal
        document.querySelectorAll('.delete-transaction').forEach(button => {
            button.addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('deleteTransactionModal'));
                document.getElementById('deleteTransactionId').value = this.dataset.id;
                modal.show();
            });
        });
        // 其他类别相关 JS 保持不变
        document.querySelectorAll('.edit-category').forEach(button => {
            button.addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
                const data = this.dataset;
                document.getElementById('editCategoryId').value = data.id;
                document.getElementById('editCategoryName').value = data.name;
                document.getElementById('editCategoryType').value = data.type;
                document.getElementById('editCategoryDescription').value = data.description;
                modal.show();
            });
        });
        document.querySelectorAll('.delete-category').forEach(button => {
            button.addEventListener('click', function() {
                const modal = new bootstrap.Modal(document.getElementById('deleteCategoryModal'));
                const data = this.dataset;
                document.getElementById('deleteCategoryId').value = data.id;
                document.getElementById('deleteCategoryName').textContent = data.name;
                modal.show();
            });
        });
    </script>
    <c:if test="${not empty error}">
        <script>
            alert('${error}');
        </script>
    </c:if>
</body>
</html> 